package com.hs.device.controller;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hs.device.dto.DetectorDto;
import com.hs.device.dto.UpdateDetectorDto;
import com.hs.device.entity.Detector;
import com.hs.device.service.IDetectorService;
import com.hs.common.api.dto.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * detector 前端控制器
 * </p>
 *
 * @author Ding
 * @since 2022-07-20
 */
@Slf4j
@Api(tags = "地磁设备模块")
@RestController
@RequestMapping("/detector")
public class DetectorController {

    @Autowired
    private IDetectorService detectorService;

    @GetMapping("/enter/{id}/{carLicensePlate}")
    @ApiOperation("车辆驶入地磁感应接口")
    public ResultVo senseNewCar(@PathVariable("id") Long id,@PathVariable("carLicensePlate") String carLicensePlate){

        return detectorService.senseNewCar(id,carLicensePlate);

    }

    @GetMapping("/out/{id}")
    @ApiOperation("车辆驶离地磁感应接口")
    public ResultVo outOneCar(@PathVariable("id") Long id) throws ParseException {

        return detectorService.outOneCar(id);

    }

    /**
     * 条件查询(地磁详情)
     * @param deviceId 地磁编号
     * @param deviceName 地磁名称
     * @param berthId 泊位id
     * @return ResultVo 结果集
     */
    @GetMapping("/condition/{current}/{size}")
    @ApiOperation("条件分页查询地磁设备列表")
    public ResultVo findDetectorByConditions(
            @PathVariable @ApiParam(name = "current", value = "当前页数") Integer current,
            @PathVariable @ApiParam(name = "size", value = "页面大小") Integer size,
             @ApiParam(name = "deviceId", value = "地磁编号")Long deviceId,
             @ApiParam(name = "deviceName", value = "地磁名称")String deviceName,
             @ApiParam(name = "berthId", value = "泊位id")Integer berthId){

        return detectorService.findDeviceByConditions(current,size,deviceId,deviceName,berthId);

    }

    /**
     * 新增地磁设备
     * @param detectorDto 地磁设备对象
     * @return
     */
    @PostMapping("/addDevice")
    @ApiOperation("新增地磁设备信息")
    public ResultVo addDevice(@RequestBody DetectorDto detectorDto){

        return detectorService.addDetector(detectorDto);
    }

    /**
     *修改地磁设备
     * @param updateDetectorDto
     * @return
     */
    @PutMapping("/updateDevice")
    @ApiOperation("修改地磁设备信息")

    public ResultVo updateDevice(@RequestBody UpdateDetectorDto updateDetectorDto){
        return detectorService.updateDevice(updateDetectorDto);
    }

    /**
     * 删除地磁设备
     * @param
     * @return
     */
    @DeleteMapping("/deleteDevice")
    @ApiOperation("删除地磁设备信息")

    public ResultVo deleteDevice(
            @RequestParam ("detectorId")@ApiParam(name = "detectorId", value = "地磁编号")Integer detectorId){
        return detectorService.deleteDevice(detectorId);
    }


    /**
     * 根据berthID条件查询未绑定泊位的地磁设备
     * @return
     */
    @GetMapping("/unbindDevice")
    @ApiOperation("查询未绑定泊位的地磁设备，限定条件：路段ID")
    public ResultVo unbindDevice(
            @RequestParam ("roadId")@ApiParam(name = "roadId", value = "路段ID")Integer roadId
    ){
        return detectorService.unbindDevice(roadId);
    }


    /**
     * 绑定泊位ID，修改地磁设备信息
     * @param detectorId
     * @param berthId
     * @return
     */
    @PutMapping("/bindDevice")
    @ApiOperation("绑定泊位ID，修改地磁设备信息")
    public ResultVo bindDevice(
            @RequestParam ("detectorId")@ApiParam(name = "detectorId", value = "地磁编号")Integer detectorId,
            @RequestParam ("berthId")@ApiParam(name = "berthId", value = "泊位id")Long berthId
    ){
        return detectorService.bindDevice(detectorId,berthId);
    }


    /**
     * 上传Excel表格里的数据到数据库
     * @param file
     * @return
     */
    @ApiOperation("上传Excel模板表格里的数据到数据库")
    @PostMapping("/importExcel")
    public String importExcel(MultipartFile file){
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            //
            HashMap<String, String> headerAlias = new HashMap<>(4);
            headerAlias.put("地磁名称", "name");
            headerAlias.put("路段id", "roadId");

            reader.setHeaderAlias(headerAlias);
            List<Detector> list = reader.read(0, 1, Detector.class);

            list.forEach(e->{
                e.setBuildTime(new Date());
                e.setStatus(1);
                e.setHaveCar(0);
            });

            //保存
            detectorService.saveBatch(list);
            return "数据插入数据库成功！";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "数据插入数据库失败！";

    }

    /**
     * 下载Ecxel模板
     * @param
     * @throws IOException
     */
    @ApiOperation("下载Ecxel模板")
    @GetMapping("/excel")
    public void outExcel(HttpServletResponse response) throws IOException {

        Workbook workbook=new HSSFWorkbook();

        // 创建一个sheet
        Sheet sh1 = workbook.createSheet("地磁设备信息模板");

        // 第一行
        Row row = sh1.createRow(0);

        row.createCell(0).setCellValue("地磁名称");
        row.createCell(1).setCellValue("路段id");

        Row row1 = sh1.createRow(1);

        row1.createCell(0).setCellValue("测试设备");
        row1.createCell(1).setCellValue("888888");


        //FileOutputStream fos = new FileOutputStream(new File("地磁设备信息模板.xls"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-disposition","attachment;filename=detector.xls");
        workbook.write(response.getOutputStream());

    }


}

